<template>
    <!-- 绘制面板 与 标记绘制-->
    <div class="g-show-media" v-if="showMidea" >
        <img class="image" :src = "showMideaUrl"></img>
        <div class="close-show-media" @click="()=>showMidea = false">×</div>
    </div>
    <div class="g-action-panel" >
        <div :class="state.currentType === 'pin' ? 'g-action-item selection' : 'g-action-item'" @click="draw('pin', true)">
            <a>
                <SvgIcon  class="icons" name="dingwei"></SvgIcon>
            </a>
        </div>
        <div :class="state.currentType === 'polyline' ? 'g-action-item selection' : 'g-action-item'"
            @click="draw('polyline', true)">
            <a>
                <SvgIcon class="icons" name="line"></SvgIcon>
            </a>
        </div>
        <div :class="state.currentType === 'polygon' ? 'g-action-item selection' : 'g-action-item'"
            @click="draw('polygon', true)">
            <a>
                <SvgIcon class="icons" name="width"></SvgIcon>
            </a>
        </div>
        <div v-if="mouseMode" class="g-action-item" @click="draw('off', false)">
            <a style="color: red;">
                <SvgIcon class="icons" name="close"></SvgIcon>
            </a>
        </div>
    </div>
</template>
<script setup lang='ts'>
import {
    deleteElementReq,
    getElementGroupsReq,
    updateElementsReq
} from '@/api/layer'
import {
    generateLineContent,
    generatePointContent,
    generatePolyContent
} from '@/utils/map-layer-utils'

import { useConnectMqtt } from '../g-map/use-connect-mqtt'
import  osstore from '@/store/modules/aliyOss'
import { onMounted, reactive, ref, computed, watch } from 'vue'
import pin from '@/assets/icons/pin-2d8cf0.svg'
import rootStore from '@/store/other/aboutDev'
import { useMouseTool } from '@/hooks/use-mouse-tool'
import { MapDoodleType, MapElementEnum } from '@/constants/map'
import { MapDoodleEnum } from '@/types/map-enum'
import { postElementsReq } from '@/api/layer'
import { uuidv4 } from '@/utils/uuid'
import { EDeviceTypeName } from '@/types'
import  settingStore from '@/store/modules/setting';
import { gcj02towgs84, wgs84togcj02 } from '@/vendors/coordtransform'
import { PostElementsBody } from '@/types/mapLayer'
import { GeojsonCoordinate, LayerResource } from '@/types/map'
import { useGMapCover } from '@/hooks/use-g-map-cover'
import { deviceTsaUpdate } from '@/hooks/use-g-map-tsa'
import { IPage } from '@/api/http/type'
import { downloadMediaFile, getMediaFiles, LookMediaFile } from '@/api/media'
import {
  DeviceOsd, DeviceStatus, DockOsd, EGear, EModeCode, GatewayOsd, EDockModeCode,
  NetworkStateQualityEnum, NetworkStateTypeEnum, RainfallEnum, DroneInDockEnum
} from '@/types/device'
import useGMapManage  from '@/store/modules/Gmap'
import { ELocalStorageKey } from '@/types/enums'
interface MediaFile {
  fingerprint: string,
  drone: string,
  payload: string,
  is_original: string,
  file_name: string,
  file_path: string,
  create_time: string,
  file_id: string,
}
const OsStore  = osstore()
const imageExtensions = ['jpg', 'jpeg', 'gif', 'png'];
const videoExtensions = ['mp4', 'wmv', 'avi', 'mov'];
const useGMapManageHook = useGMapManage()
const workspaceId = localStorage.getItem(ELocalStorageKey.WorkspaceId)!
let showMidea = ref(false)
let useSettingStore = settingStore() ;
const showMideaUrl = ref()
const scorllHeight = ref()
const deviceTsaUpdateHook = deviceTsaUpdate()

const store = rootStore
const mapLayers = ref(store.state.Layers)
const state = reactive({
    currentType: '',
    coverIndex: 0
})
let useGMapCoverHook = useGMapCover()

const useMouseToolHook = useMouseTool()

const mouseMode = ref(false)
const drawVisible = computed(() => {
    return store.state.drawVisible
})
const shareId = computed(() => {
    return store.state.layerBaseInfo.share
})
const osdVisible = computed(() => {
      return store.state.osdVisible
})
const paginationProp = reactive({
    pageSizeOptions: ['20', '50', '100'],
    showQuickJumper: true,
    showSizeChanger: true,
    pageSize: 50,
    current: 1,
    total: 0
  })
const body: IPage = {
    page: 1,
    total: 0,
    page_size: 50
}
async function getFiles () {
    let mediaData
    await getMediaFiles(workspaceId, body).then(res => {
        mediaData= res.data.list
        paginationProp.total = res.data.pagination.total
        paginationProp.current = res.data.pagination.page
    })
    return mediaData
}

const str: string = '--'
watch(()=>useSettingStore.showTable,()=>{//点击隐藏图标
    useGMapCoverHook.showLable();
    showMidea.value = false
})
watch(()=>useSettingStore.showPic,async ()=>{//点击展示图片
    useGMapCoverHook.showPic()
    let mediaData =await  getFiles()
    mediaData.forEach(element=> {   
        const coordinates = wgs84togcj02(
            element.longitude,element.latitude
                    )
        const pin = useGMapCoverHook.updatePicElement(element.file_name,element.file_id,coordinates )
        pin.on('click', async () => {//单击点后绑定的事件
            showMidea.value = true

            const extension = element.file_name.split('.')[1].toLowerCase()
            if (imageExtensions.includes(extension)) {//image 
                let url = await OsStore.toGetUrl(element.object_key)               
                showMideaUrl.value = url
            }       
            // 判断文件扩展名是否在视频扩展名数组中
            if (videoExtensions.includes(extension)) {//获取视频第一帧
                let url = await OsStore.toGetMediaUrl(element.object_key)  
                console.log(url,"dddddddddddddd");
                
                funShowMidea(element.file_name,url)
            }
            })
    })

})
const funShowMidea = (name:string,res:string)=>{
    showMideaUrl.value = res


}
const deviceInfo = reactive({
      gateway: {
        capacity_percent: str,
        transmission_signal_quality: str,
      } as GatewayOsd,
      dock: {

      } as DockOsd,
      device: {
        gear: -1,
        mode_code: EModeCode.Disconnected,
        height: str,
        home_distance: str,
        horizontal_speed: str,
        vertical_speed: str,
        wind_speed: str,
        wind_direction: str,
        elevation: str,
        position_state: {
          gps_number: str,
          is_fixed: 0,
          rtk_number: str
        },
        battery: {
          capacity_percent: str,
          landing_power: str,
          remain_flight_time: 0,
          return_home_power: str,
        },
        latitude: 0,
        longitude: 0,
      } as DeviceOsd
    })
watch(
    () => store.state.Layers,
    newData => {
        mapLayers.value = newData
        
    },
    {
        deep: true
    }
)
watch(() => store.state.deviceStatusEvent,
      data => {
        if (Object.keys(data.deviceOnline).length !== 0) {
            useGMapCoverHook.initMarker(data.deviceOnline.domain, data.deviceOnline.device_callsign, data.deviceOnline.sn)
          store.state.deviceStatusEvent.deviceOnline = {} as DeviceStatus
        }
        if (Object.keys(data.deviceOffline).length !== 0) {
            useGMapCoverHook.removeMarker(data.deviceOffline.sn)
          if ((data.deviceOffline.sn === osdVisible.value.sn) || (osdVisible.value.is_dock && data.deviceOffline.sn === osdVisible.value.gateway_sn)) {
            osdVisible.value.visible = false
            store.commit('SET_OSD_VISIBLE_INFO', osdVisible)
          }
          store.state.deviceStatusEvent.deviceOffline = {}
        }
      },
      {
        deep: true
    })

watch(() => store.state.deviceState, data => {
    if (data.currentType === EDeviceTypeName.Gateway && data.gatewayInfo[data.currentSn]) {
    deviceTsaUpdateHook.moveTo(data.currentSn, data.gatewayInfo[data.currentSn].longitude, data.gatewayInfo[data.currentSn].latitude)
    if (osdVisible.value.visible && osdVisible.value.gateway_sn !== '') {
        deviceInfo.gateway = data.gatewayInfo[osdVisible.value.gateway_sn]
    }
    }
    if (data.currentType === EDeviceTypeName.Aircraft && data.deviceInfo[data.currentSn]) {
    deviceTsaUpdateHook.moveTo(data.currentSn, data.deviceInfo[data.currentSn].longitude, data.deviceInfo[data.currentSn].latitude)
    if (osdVisible.value.visible && osdVisible.value.sn !== '') {
        deviceInfo.device = data.deviceInfo[osdVisible.value.sn]
    }
    }
    if (data.currentType === EDeviceTypeName.Dock && data.dockInfo[data.currentSn]) {
    deviceTsaUpdateHook.initMarker(EDeviceTypeName.Dock, EDeviceTypeName[EDeviceTypeName.Dock], data.currentSn, data.dockInfo[data.currentSn].basic_osd?.longitude, data.dockInfo[data.currentSn].basic_osd?.latitude)
    if (osdVisible.value.visible && osdVisible.value.is_dock && osdVisible.value.gateway_sn !== '') {
        deviceInfo.dock = data.dockInfo[osdVisible.value.gateway_sn]
        deviceInfo.device = data.deviceInfo[deviceInfo.dock.basic_osd.sub_device?.device_sn ?? osdVisible.value.sn]
    }
    }
}, {
    deep: true
    })

watch(() => store.state.wsEvent,
    newData => {
    const useGMapCoverHook = useGMapCover()
    const event = newData
    let exist = false
    if (Object.keys(event.mapElementCreat).length !== 0) {
        console.log(event.mapElementCreat)
        const ele = event.mapElementCreat
        store.state.Layers.forEach(layer => {
        layer.elements.forEach(e => {
            if (e.id === ele.id) {
            exist = true
            console.log('true')
            }
        })
        })
        if (exist === false) {
        setLayers({
            id: ele.id,
            name: ele.name,
            resource: ele.resource
        })

        updateCoordinates('wgs84-gcj02', ele)
        const data = { id: ele.id, name: ele.name }
        if (MapElementEnum.PIN === ele.resource?.type) {
            useGMapCoverHook.init2DPin(
            ele.name,
            ele.resource.content.geometry.coordinates,
            ele.resource.content.properties.color,
            data
            )
        } else if (MapElementEnum.LINE === ele.resource?.type) {
            useGMapCoverHook.initPolyline(
            ele.name,
            ele.resource.content.geometry.coordinates,
            ele.resource.content.properties.color,
            data)
        } else if (MapElementEnum.POLY === ele.resource?.type) {
            useGMapCoverHook.initPolygon(
            ele.name,
            ele.resource.content.geometry.coordinates,
            ele.resource.content.properties.color,
            data)
        }
        }

        store.state.wsEvent.mapElementCreat = {}
    }
    if (Object.keys(event.mapElementUpdate).length !== 0) {
        console.log(event.mapElementUpdate)
        console.log('该功能还未实现，请开发商自己增加')
        store.state.wsEvent.mapElementUpdate = {}
    }
    if (Object.keys(event.mapElementDelete).length !== 0) {
        console.log(event.mapElementDelete)
        console.log('该功能还未实现，请开发商自己增加')
        store.state.wsEvent.mapElementDelete = {}
    }
    },
    {
    deep: true
    })

function updateWgs84togcj02() {
    const layers = mapLayers.value
    layers.forEach(item => {
        if (item.elements) {
            item.elements.forEach(ele => {
                updateCoordinates('wgs84-gcj02', ele)
            })
        }
    })
    return layers
}
async function getElementGroups(type?: string) {
    const result = await getElementGroupsReq({
        groupId: '',
        isDistributed: true
    })
    mapLayers.value = result.data
    mapLayers.value = updateWgs84togcj02()
    if (type && type === 'init') {        
        store.dispatch('setLayerInfo', mapLayers.value)
    }
    store.commit('SET_LAYER_INFO', mapLayers.value)
}



function draw(type: MapDoodleType, bool: boolean) {
    state.currentType = type
    useMouseToolHook.mouseTool(type, getDrawCallback)
    mouseMode.value = bool
}


function getDrawCallback({ obj }) {
    switch (state.currentType) {
        case MapDoodleEnum.PIN:
            postPinPositionResource(obj)
            break
        case MapDoodleEnum.POLYLINE:
            postPolylineResource(obj)
            break
        case MapDoodleEnum.POLYGON:
            postPolygonResource(obj)
            break
        default:
            break
    }
}
async function postPinPositionResource(obj) {
    const req = getPinPositionResource(obj)
    setLayers(req)
    const coordinates = req.resource.content.geometry.coordinates
    updateCoordinates('gcj02-wgs84', req);
    (req.resource.content.geometry.coordinates as GeojsonCoordinate).push((coordinates as GeojsonCoordinate)[2])
    const result = await postElementsReq(shareId.value, req)
    obj.setExtData({ id: req.id, name: req.name })
    store.state.coverList.push(obj)
    // console.log(store.state.coverList)
}
async function postPolylineResource(obj) {
    const req = getPolylineResource(obj)
    setLayers(req)
    updateCoordinates('gcj02-wgs84', req)
    const result = await postElementsReq(shareId.value, req)
    obj.setExtData({ id: req.id, name: req.name })
    store.state.coverList.push(obj)
    // console.log(store.state.coverList)
}
async function postPolygonResource(obj) {
    const req = getPoygonResource(obj)
    setLayers(req)
    updateCoordinates('gcj02-wgs84', req)
    const result = await postElementsReq(shareId.value, req)
    obj.setExtData({ id: req.id, name: req.name })
    store.state.coverList.push(obj)
    // console.log(store.state.coverList)
}

function getPinPositionResource(obj) {
    const position = obj.getPosition()
    const resource = generatePointContent(position)
    const name = obj._originOpts.title
    const id = uuidv4()
    return {
        id,
        name,
        resource
    }
}
function getPolylineResource(obj) {
    const path = obj.getPath()
    const resource = generateLineContent(path)
    const { name, id } = getBaseInfo(obj._opts)
    return {
        id,
        name,
        resource
    }
}
function getPoygonResource(obj) {
    const path = obj.getPath()
    const resource = generatePolyContent(path)
    const { name, id } = getBaseInfo(obj._opts)
    return {
        id,
        name,
        resource
    }
}
function getBaseInfo(obj) {
    const name = obj.title
    const id = uuidv4()
    return { name, id }
}
function setLayers(resource: PostElementsBody) {
    const layers = store.state.Layers
    const layer = layers.find(item => item.id.includes(shareId.value))
    // layer.id = 'private_layer' + uuidv4()
    // layer?.elements.push(resource)
    if (layer?.elements) {
        (layer?.elements as any[]).push(resource)
    }
    store.commit('SET_LAYER_INFO', layers)
}
function closeLivestreamOthers() {
    store.commit('SET_LIVESTREAM_OTHERS_VISIBLE', false)
}
function closeLivestreamAgora() {
    store.commit('SET_LIVESTREAM_AGORA_VISIBLE', false)
}
function updateCoordinates(transformType: string, element: any) {
    const geoType = element.resource?.content.geometry.type
    const type = element.resource?.type as number
    if (element.resource) {
        if (MapElementEnum.PIN === type) {
            const coordinates = element.resource?.content.geometry
                .coordinates as GeojsonCoordinate
            if (transformType === 'wgs84-gcj02') {
                const transResult = wgs84togcj02(
                    coordinates[0],
                    coordinates[1]
                ) as GeojsonCoordinate
                element.resource.content.geometry.coordinates = transResult
            } else if (transformType === 'gcj02-wgs84') {
                const transResult = gcj02towgs84(
                    coordinates[0],
                    coordinates[1]
                ) as GeojsonCoordinate
                element.resource.content.geometry.coordinates = transResult
            }
        } else if (MapElementEnum.LINE === type) {
            const coordinates = element.resource?.content.geometry
                .coordinates as GeojsonCoordinate[]
            if (transformType === 'wgs84-gcj02') {
                coordinates.forEach((coordinate, i, arr) => {
                    arr[i] = wgs84togcj02(
                        coordinate[0],
                        coordinate[1]
                    ) as GeojsonCoordinate
                })
            } else if (transformType === 'gcj02-wgs84') {
                coordinates.forEach((coordinate, i, arr) => {
                    arr[i] = gcj02towgs84(
                        coordinate[0],
                        coordinate[1]
                    ) as GeojsonCoordinate
                })
            }
            element.resource.content.geometry.coordinates = coordinates
        } else if (MapElementEnum.POLY === type) {
            const coordinates = element.resource?.content.geometry
                .coordinates[0] as GeojsonCoordinate[]
            if (transformType === 'wgs84-gcj02') {
                coordinates.forEach((coordinate, i, arr) => {
                    arr[i] = wgs84togcj02(
                        coordinate[0],
                        coordinate[1]
                    ) as GeojsonCoordinate
                })
            } else if (transformType === 'gcj02-wgs84') {
                coordinates.forEach((coordinate, i, arr) => {
                    arr[i] = gcj02towgs84(
                        coordinate[0],
                        coordinate[1]
                    ) as GeojsonCoordinate
                })
            }
            element.resource.content.geometry.coordinates = [coordinates]
        }
    }

    return {
        draw,
        mouseMode,
        drawVisible,
        // livestreamOthersVisible,
        // livestreamAgoraVisible,
        // osdVisible,
        pin,
        state,
        // M30,
        // deviceInfo,
        // EGear,
        // EModeCode,
        // str,
        // EDockModeCode,
        // dockControlPanelVisible,
        // setDockControlPanelVisible,
        // onCloseControlPanel,
        // NetworkStateTypeEnum,
        // NetworkStateQualityEnum,
        // RainfallEnum,
        // DroneInDockEnum,
        closeLivestreamOthers,
        closeLivestreamAgora,
        // qualityStyle,
    }
}
function initMapCover () {
  mapLayers.value.forEach(item => {
    if (item.elements) {
      setMapCoverByElement(item.elements)
    }
  })
}
async function getAllElement () {//获取并绘制标记
useGMapCoverHook.initMapLableGroup()
  getElementGroups('init')

  setTimeout(() => {
    useGMapCoverHook = useGMapCover()
    initMapCover()
  }, 1000)
}
function setMapCoverByElement (elements: LayerResource[]) {
  elements.forEach(element => {
    const name = element.name
    const color = element.resource?.content.properties.color
    const type = element.resource?.type as number
    updateMapElement(element, name, color)
  })
  

}
function updateMapElement (
  element: LayerResource,
  name: string,
  color: string | undefined
) {
  const geoType = element.resource?.content.geometry.type
  const id = element.id
  const type = element.resource?.type as number
  if (MapElementEnum.PIN === type) {
    const coordinates = element.resource?.content.geometry
      .coordinates as GeojsonCoordinate
    useGMapCoverHook.updatePinElement(id, name, coordinates, color)
  } else if (MapElementEnum.LINE === type && geoType === 'LineString') {
    const coordinates = element.resource?.content.geometry
      .coordinates as GeojsonCoordinate[]
    useGMapCoverHook.updatePolylineElement(id, name, coordinates, color)
  } else if (MapElementEnum.POLY === type && geoType === 'Polygon') {
    const coordinates = element.resource?.content.geometry
      .coordinates as GeojsonCoordinate[][]
    useGMapCoverHook.updatePolygonElement(id, name, coordinates, color)
  }
}
useConnectMqtt()
  onMounted(async() => {///初始化
    await useGMapManageHook.initMap('container')
    getAllElement()
})
</script>

<style scoped lang='scss'>
.g-show-media{
    position: absolute;
    right: 0;
    bottom: 2px;
    width: 600px;
    height: 350px;
    display: flex;
    z-index: 102;
    background-color: rgba(242, 242, 242, 0.774);
    .close-show-media{
        color: rgb(255, 255, 255);
        line-height: 28px;
        text-align: center;
        font-size: 20px;
        position: absolute;
        right: 10px;
        top: 10px;
        height: 30px;
        width: 30px;
        border-radius: 50%;
        background-color: rgb(32, 111, 180);
        cursor: pointer;
    }
    .image{
        width: auto !important;
        height: 350px;
        margin: 0 auto;
        overflow: hidden;


    }
}
.g-action-panel {
    position: absolute;
    top: 150px;
    right: 20px !important;
    z-index: 100;

    .g-action-item {
        box-sizing: border-box;
        width: 28px;
        height: 28px;
        cursor:pointer;
        background: white;
        color: $primary;
        border-radius: 2px;
        line-height: 28px;
        text-align: center;
        margin-bottom: 2px;
        .icons{
            width: 80% !important;

        }
    }

    .g-action-item:hover {
        border: 1px solid $primary;
        border-radius: 2px;
    }
}

.selection {
    border: 1px solid $primary;
    border-radius: 2px;
}

// antd button 光晕</style >@/store/modules/aliyOss
